package com.youngball.business.service.qiniu;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.youngball.business.entity.SysQiniu;
import com.youngball.business.mapper.SysQiniuMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * Created by liaopingzhu on 2017/1/17.
 */
@Component
public class SysQiniuServiceImpl implements SysQiniuService {

    private static final Logger logger1 = LoggerFactory.getLogger("myTest1");
    private static final String BUCKET_NAME = "alpz-1993";
    private static final String PREFFIX = "http://o9m7chf87.bkt.clouddn.com/";

    @Autowired
    private SysQiniuMapper sysQiniuMapper;

    /**
     * 简单上传文件
     * @param matchPhoto
     * @return
     * @throws IOException
     */
    @Override
    public String upload(String matchPhoto) throws IOException {
        String photoUrl = "";
        //设置好账号的ACCESS_KEY和SECRET_KEY
        String ACCESS_KEY = this.getInfo().getAccessKey();
        String SECRET_KEY = this.getInfo().getSecretKey();
        //要上传的空间
        String bucketname = BUCKET_NAME;
        //密钥配置
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String FilePath = matchPhoto;
        //上传到七牛后保存的文件名
        String key = System.currentTimeMillis() + setSuffixes(matchPhoto);
        UploadManager uploadManager = new UploadManager();
        String token = auth.uploadToken(bucketname);
        try{
            Response response = uploadManager.put(FilePath,key,token);
            logger1.debug("七牛上传文件body信息"+response.bodyString());
            photoUrl = PREFFIX + key;
        }catch (QiniuException e){
            Response r = e.response;
            logger1.debug("七牛上传文件请求失败时打印的异常的信息"+r.toString());
            try {
                logger1.debug("七牛上传文件响应的文本信息"+r.bodyString());
            } catch (QiniuException e1) {
                e1.printStackTrace();
            }
        }
        return photoUrl;
    }

    /**
     * 生成下载链接
     * @return
     */
    public String download(){
        return null;
    }

    @Override
    public SysQiniu getInfo() {
        List<SysQiniu> sysQinius = sysQiniuMapper.selectByBucketName(BUCKET_NAME);
        return sysQinius.get(0);
    }

    /**
     * 设置文件后缀
     * @param url
     * @return
     */
    public String setSuffixes(String url){
        String suf = "";
//        String[] urlStr = url.split(".");
        int k = url.length();
        for(int i=0;i<k;i++){
            if(".".equals(url.substring(i,i+1))){
                suf = url.substring(i,url.length());
            }
        }
        return suf;
    }
}
